package rd.android.hardcore.engine 
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	import rd.android.hardcore.event.SoundSystemEvent;
	
	/**
	 * Sound System
	 * instance : Main
	 * 
	 * @author Romain
	 */
	public class HardcoreGhettoSoundSystem extends EventDispatcher
	{
		
		/* VAR */
		//public var conteneurSon		: Sound;
		public var canal			: SoundChannel;
		public var volumeManager	: SoundTransform;
		
		private var currentVolume 	: Number;
		private var soundCpt		: int = 0;
		private var sndPlaying		: Boolean = false;
		
		private var a_sndChannel	: Array = [];
		
		
		
		/* Hardcore Ghetto SoundSystem */
		public function HardcoreGhettoSoundSystem() 
		{
			currentVolume = 1;
			
			volumeManager 	= new SoundTransform();
			
			volumeManager.volume = currentVolume;
		}
		
		/* Play Sound */
		public function playSound( evt : SoundSystemEvent ) : void
		{
			var conteneurSon:Sound = new Sound();
			
			var fichierMP3:URLRequest = new URLRequest( evt.track.file );
			
			conteneurSon.addEventListener(IOErrorEvent.IO_ERROR, handleError, false, 0, true);
			conteneurSon.load(fichierMP3);
			
			sndPlaying = true;
			canal = conteneurSon.play();
			a_sndChannel.push(canal);
			canal.addEventListener(Event.SOUND_COMPLETE, closeSound);
			canal.soundTransform = volumeManager;
			soundCpt++;
			
			conteneurSon = null;
		}
		
		
		/* Error Handler */
		private function handleError(e:IOErrorEvent):void 
		{
			reGenChannel();
		}
		
		public function closeSound( evt : Event ) : void
		{
			if(soundCpt !=0)	soundCpt--;
			
			if ((soundCpt == 0 || evt == null) && sndPlaying) {
				while (a_sndChannel.length > 0) {
					canal = a_sndChannel.pop();
					canal.stop();
					canal.removeEventListener(Event.SOUND_COMPLETE, closeSound);
					canal = null;
				}
				dispatchEvent(new SoundSystemEvent(SoundSystemEvent.STOP_SOUND, null));
				
				soundCpt = 0;
				sndPlaying = false;
			}
		}
		
		
		/* Channel Handler */
		private function reGenChannel() : void
		{
			if (canal) canal.stop();
			
			canal 			= new SoundChannel();
			//conteneurSon 	= new Sound();
			
			volumeManager 	= new SoundTransform(currentVolume);
		}
		
	}

}